# -*- coding: utf-8 -*-
from flask import Flask, flash, redirect, render_template, request, url_for, session, jsonify
import subprocess, json

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/loaddata', methods=['GET', 'POST'])
def loaddata():
    username = request.form['username']
    password = request.form['password']
    scrapy_cmd = "scrapy crawl gs -a username=%s -a password=%s" % (username, password)
    p = subprocess.Popen(scrapy_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    ret = p.wait()
    # print p.stderr.read()

    if ret or p.stderr.read() != '':
        return render_template('index.html', error='爬虫错误')
        # return jsonify(code=201, messsage='爬虫错误')
    # return result if result.index('用户名或密码错误') < 0 else jsonify(code=202, message='用户名或密码错误')
    result = p.stdout.read()
    print result

    print result.find('用户名或密码错误')
    if result.find('用户名或密码错误') < 0:
        # grades = json.loads(result, encoding="utf-8")
        return render_template('grade.html', grades=json.loads(result, encoding='utf-8'))
    else:
        return render_template('index.html', error='用户名或密码错误')


if __name__ == '__main__':
    app.run()
